package com.andy.blog.dal.service.impl;

import com.andy.blog.common.exception.BlogServiceException;
import com.andy.blog.common.reponse.BlogResultCode;
import com.andy.blog.common.utils.DateUtils;
import com.andy.blog.common.utils.SecurityUtils;
import com.andy.blog.common.utils.TransformUtils;
import com.andy.blog.dal.domain.SysMenuDO;
import com.andy.blog.dal.mapper.SysMenuMapper;
import com.andy.blog.dal.mapper.SysRoleMenuMapper;
import com.andy.blog.dal.service.SysMenuDalService;
import com.andy.blog.dal.vo.SysMenuVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * Created by andy on 2023-04-05 11:38
 */
@Service
public class SysMenuDalServiceImpl implements SysMenuDalService {

    @Resource
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;


    private QueryWrapper<SysMenuDO> buildQueryWrapper(SysMenuVO sysMenuVO, Long userId) {
        QueryWrapper<SysMenuDO> lambdaQueryWrapper = new QueryWrapper<>();
        lambdaQueryWrapper
                .eq(Objects.nonNull(userId), "ur.user_id", userId)
                .lambda()
                .like(StringUtils.isNotBlank(sysMenuVO.getMenuName()), SysMenuDO::getMenuName, sysMenuVO.getMenuName())
                .eq(StringUtils.isNotBlank(sysMenuVO.getVisible()), SysMenuDO::getVisible, sysMenuVO.getVisible())
                .eq(StringUtils.isNotBlank(sysMenuVO.getStatus()), SysMenuDO::getStatus, sysMenuVO.getStatus())
                .orderByAsc(SysMenuDO::getParentId)
                .orderByAsc(SysMenuDO::getOrderNum);
        return lambdaQueryWrapper;
    }

    @Override
    public List<SysMenuDO> selectMenuListByUserId(SysMenuVO sysMenuVO, Long userId) {
        QueryWrapper<SysMenuDO> doQueryWrapper = buildQueryWrapper(sysMenuVO, userId);

        return menuMapper.selectMenuListByUserId(doQueryWrapper);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询权限
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        List<String> perms = menuMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<SysMenuDO> selectMenuTreeByUserId(Long userId) {
        return menuMapper.selectMenuTreeByUserId(userId);
    }


    @Override
    public List<Long> selectMenuListByRoleId(Long roleId, Boolean menuCheckStrictly) {
        return menuMapper.selectMenuListByRoleId(roleId, menuCheckStrictly);
    }


    @Override
    public SysMenuDO selectMenuById(Long id) {
        return menuMapper.selectMenuById(id);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId(Long menuId) {
        LambdaQueryWrapper<SysMenuDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysMenuDO::getParentId, menuId);
        Long result = menuMapper.selectCount(lambdaQueryWrapper);
        return result > 0;
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean checkMenuExistRole(Long menuId) {
        int result = roleMenuMapper.checkMenuExistRole(menuId);
        return result > 0;
    }

    /**
     * 新增保存菜单信息
     *
     * @param sysMenuVO 菜单信息
     */
    @Override
    public void insertMenu(SysMenuVO sysMenuVO) {
        SysMenuDO sysMenuDO = TransformUtils.transform(sysMenuVO, SysMenuDO.class);

        sysMenuDO.setCreateBy(SecurityUtils.getUsername());
        sysMenuDO.setCreateTime(DateUtils.getCurrentDate());

        int row;
        try {
            row = menuMapper.insert(sysMenuDO);
        } catch (Exception e) {
            throw new BlogServiceException(BlogResultCode.BLOG_000100, e);
        }

        if (row <= 0) {
            throw new BlogServiceException(BlogResultCode.BLOG_000100);
        }
    }

    @Override
    public void updateMenu(SysMenuVO sysMenuVO) {
        SysMenuDO sysMenuDO = TransformUtils.transform(sysMenuVO, SysMenuDO.class);

        sysMenuDO.setUpdateBy(SecurityUtils.getUsername());
        sysMenuDO.setUpdateTime(DateUtils.getCurrentDate());

        int row;
        try {
            row = menuMapper.updateById(sysMenuDO);
        } catch (Exception e) {
            throw new BlogServiceException(BlogResultCode.BLOG_000101, e);
        }

        if (row <= 0) {
            throw new BlogServiceException(BlogResultCode.BLOG_000101);
        }
    }

    /**
     * 删除菜单管理信息
     */
    @Override
    public void deleteMenuById(Long menuId) {

        int row;
        try {
            row = menuMapper.deleteById(menuId);
        } catch (Exception e) {
            throw new BlogServiceException(BlogResultCode.BLOG_000101, e);
        }

        if (row <= 0) {
            throw new BlogServiceException(BlogResultCode.BLOG_000101);
        }
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param sysMenuVO 菜单信息
     * @return 结果
     */
    @Override
    public boolean checkMenuNameUnique(SysMenuVO sysMenuVO) {
        LambdaQueryWrapper<SysMenuDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysMenuDO::getMenuName, sysMenuVO.getMenuName())
                .eq(SysMenuDO::getParentId, sysMenuVO.getParentId())
                .last("limit 1");
        SysMenuDO sysMenuDO = menuMapper.selectOne(lambdaQueryWrapper);
        if (Objects.nonNull(sysMenuDO) && !Objects.equals(sysMenuDO.getId(), sysMenuVO.getId())) {
            return false;
        }
        return true;
    }

    @Override
    public List<SysMenuDO> selectMenuTreeAll() {
        return menuMapper.selectMenuTreeAll();
    }
}
